package com.stox.ui.javafx.navigator.model;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javafx.collections.ObservableList;
import javafx.scene.control.TreeItem;

import com.stox.client.ExchangeClient;
import com.stox.client.ScripClient;
import com.stox.model.AbstractModel;
import com.stox.model.Country;
import com.stox.model.Exchange;

public class CountryTreeItem extends AbstractModelTreeItem<String> {

	private Country country;
	private ScripClient scripClient;
	private ExchangeClient exchangeClient;
	private List<Exchange> exchanges;

	public CountryTreeItem(Country country, ExchangeClient exchangeClient, ScripClient scripClient) {
		super.setValue(country.getName());
		this.country = country;
		this.scripClient = scripClient;
		this.exchangeClient = exchangeClient;
	}
	
	
	@Override
	public AbstractModel getModel() {
		return country;
	}
	
	@Override
	public ObservableList<TreeItem<String>> getChildren() {
		loadExchanges();
		return super.getChildren();
	}
	
	@Override
	public boolean isLeaf() {
		return false;
	}
	
	private void loadExchanges() {
		if(null == exchanges || exchanges.isEmpty()) {
			exchanges = exchangeClient.findByCountryCode(country.getCode());
			Collections.sort(exchanges);
			List<ExchangeTreeItem> exchangeTreeItems = new ArrayList<ExchangeTreeItem>(exchanges.size());
			for(Exchange exchange : exchanges) {
				exchangeTreeItems.add(new ExchangeTreeItem(exchange, scripClient));
			}
			super.getChildren().setAll(exchangeTreeItems);
		}
	}
	
}
